package org.qiuqiu.utils;

import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.junit.Test;
import org.qiuqiu.vo.User;



public class SendEmailUtils {
	private static final String FROM = "1103757643@qq.com";
	private static final String PASSWORD = "1103757643good";

	// 发送邮件方法
	
	public static void sendEmail(User user,HttpServletRequest rs) throws UnknownHostException {
		SimpleEmail email = new SimpleEmail();
		email.setTLS(true);
		email.setHostName("smtp.qq.com"); // 发送方开通服务
		email.setAuthentication(FROM, PASSWORD); // 用户名和密码
		try {
			email.addTo(user.getEmail()); // 接收方
			email.setFrom(FROM); // 发送方
			email.setSubject("登录论坛的账户激活邮件"); // 标题
			email.setCharset("UTF-8");
			email.setMsg("论坛邮件激活，请点击以下链接完成激活：" + getUrl(user,rs)); // 内容
			email.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}

	// 获取链接
	private static String getUrl(User user,HttpServletRequest re) throws UnknownHostException {
		 String basePath = re.getScheme() + "://" + re.getServerName() + ":"
					+ re.getServerPort() + re.getContextPath() + "/";
		
		String url = basePath+"user/active?id=" + user.getUserid()
				+ "&checkcode=" + getcheckcode(user);
		return url;
	}

	// 生成校验码
	public static String getcheckcode(User user) {
		String userName = user.getUsername();
		return MD5Utils.md5(userName);
	}

}